from collections import defaultdict
from operator import itemgetter

from utils.http_requester import HttpRequester


def group_sor_decorator(func):
    def wrapper(*args, **kwargs):
        grouped_data = defaultdict(list)
        data = func()
        # 遍历了excel读取出来的原始数据
        for story in data:
            grouped_data[story["story"]].append(story)

        # 按照order值进行排序
        # sorted_grouped_data = {}
        # for story, item in grouped_data.items():
        #     sorted_grouped_data[story] = sorted(item, key=itemgetter("order"))
        sorted_grouped_data = {story: sorted(item, key=itemgetter("order")) for story, item in grouped_data.items()}

        # 把数据结构还原成原始的
        res_data = []
        for value in sorted_grouped_data.values():
            res_data.extend(value)
        return res_data
    return wrapper


# 实现单列模式的装饰器
def singleton(cls):
    instance = {}

    def get_instance(*args, **kwargs):
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        return instance[cls]
    return get_instance


# 通过装饰器简化调用
def http_request_wrapper(func):
    def wrapper(*args, **kwargs):
        data = func(*args, **kwargs)
        return HttpRequester().send_request(**data)
    return wrapper